/*!
 * DOS测试控制类
 *
 * 版权所有 2017 陈学芹 联系方式: 7219530@qq.com
 *
 * 本软件在GNU LGPL-V2.1协议下发布，欢迎使用.
 */
const logger = require('../lib/logger')
const _ = require('lodash')

FloodController = function () {
  this.type = ''
  this.state = 'idle'
  this.target = ''
}

FloodController.prototype = {
  constructor: FloodController,
  init: function () {
    this.agents = []
  },

  getState: function () {
    return {
      state: this.state,
      type: this.type
    }
  },

  addAgent: function (agent) {
    this.agents.push(agent)
  },

  getAgents: function () {
    return _.clone(this.agents)
  },

  removeAgent: function (agent) {
    let removedAgent = _.remove(this.agents, function (item) {
      return agent.host === item.host
    })
    if (removedAgent.length === 1) {
      return 0
    } else {
      return -1
    }
  },

  findAgent: function (selector) {
    return _.find(this.agents, selector)
  },

  startFlood: function (target, option) {
    if (this.state !== 'idle') {
      throw new Error(`invalid state ${this.state}`)
    }
    const ipRegx = /^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/
    const DefaultSpeed = 1000
    if (!target || !target.match(ipRegx)) { throw new Error(`invalid ipAddr ${target}`) }
    if (!option.speed || isNaN(option.speed) || option.speed < 0) { option.speed = DefaultSpeed }
    _.forEach(this.agents, function (agent) {
      agent.start(target, option)
    })
    this.state = 'started'
  },

  stopFlood: function () {
    if (this.state !== 'started') {
      throw new Error(`invalid state ${this.state}`)
    }

    _.forEach(this.agents, function (agent) {
      agent.stop()
    })
    this.state = 'idle'
  },

  getTrafficStat: function () {
    let packetSent = 0
    let byteSent = 0

    _.forEach(this.agents, function (agent) {
      let stat = agent.getTraffic()

      packetSent += stat.packetSent
      byteSent += stat.byteSent
      logger.debug('agent %s packetSent %d byteSent %d', agent.host, stat.packetSent, stat.byteSent)
    })
    logger.debug('packetSent = %d byteSent = %d', packetSent, byteSent)
    return {
      packetSent: packetSent,
      byteSent: byteSent
    }
  }
}

module.exports = new FloodController()
